<script setup>
import { computed, ref, watch, h } from 'vue';
import { message, Cascader } from 'ant-design-vue';
import { notification } from 'ant-design-vue';
import { phoneRule, emailRule } from '@/utils/checkRule.js'
import api from '@/api/index.js'

const emits = defineEmits(['close', 'init', 'reload'])
const props = defineProps({
  curRow: {
    type: Object,
    default: () => ({})
  },
  faMenuSltOpt: {
    type: Array,
    default: () => ([])
  },
  isDetail: {
    type: Boolean,
    default: false
  },
})
// 弹窗标题
const title = computed(() => {
  if (props.isDetail) {
    return '用户详情'
  }
  if (props.curRow.id) {
    return '编辑数据'
  }
  return '新增数据'
})
// 表单数据
const formData = ref({
  name: '',
  roles: [],
  email: '',
  phone: '',
  userName: '',
  departments: [],
})
// 角色可选项
const roleOpt = ref([])
// 基地可选项
const depTreeOpt = ref([])
// 同步表格数据到表单数据内
watch(() => props.curRow, async (val) => {
  if (val.id) {
    const { resultObject } = await api.getUserInfo({ id: val.id })
    formData.value = { ...formData.value, ...resultObject }
  } else {
    formData.value = { ...val }
  }
}, { deep: true, immediate: true })
// 是否显示弹窗
const show = ref(false);
// 弹窗显示状态切换时触发
const afterOpenChange = bool => {
  if (!bool) {
    formData.value = {
      name: '',
      roles: [],
      email: '',
      phone: '',
      userName: '',
      departments: [],
    }
    emits('close')
  }
};
// 提交按钮loading状态
const submitLoading = ref(false)
// 编辑数据
const emitItem = async (info) => {
  submitLoading.value = true
  const params = { ...formData.value, ...info }
  await api.editUser(params)
  message.success('编辑成功');
  show.value = false
  setTimeout(() => {
    submitLoading.value = false
  }, 30);
  emits('reload')
}
// 新增数据
const addItem = async (info) => {
  submitLoading.value = true
  const params = {
    ...formData.value, ...info,
    password: '123456'
  }
  await api.addUser(params)
  notification.success({
    message: '用户新增成功！',
    description: h('span', {}, '登录账号：',
      h('span', { style: { color: '#ff0000' } }, info.userName),
      h('br', {}, ''),
      '默认密码：',
      h('span', { style: { color: '#ff0000' } }, '123456'),
    ),
    duration: 0,
  });
  show.value = false
  setTimeout(() => {
    submitLoading.value = false
  }, 30);
  emits('reload')
}
// 表单提交，验证通过了
const onFinish = values => {
  if (formData.value.id) {
    emitItem(values)
  } else {
    addItem(values)
  }
};
// 验证失败
const onFinishFailed = errorInfo => {
  console.log('Failed:', errorInfo);
};
// 获取角色可选项
const getRoleOpt = async () => {
  const { data: { records } } = await api.getRoleList({ size: 9999 })
  roleOpt.value = records.map(item => ({ label: item.name, value: item.id }))
}
// 获取部门树结构
const getDepTree = async () => {
  const { resultObject } = await api.getDepTree()
  depTreeOpt.value = resultObject
}
// 打开弹窗
const open = () => {
  getRoleOpt()
  getDepTree()
  show.value = true;
};
// 关闭弹窗
const close = () => {
  show.value = false;
};
// 表单节点
const formRef = ref()
// 提交表单
const submit = () => {
  formRef.value
    .validateFields()
    .then(onFinish)
    .catch(onFinishFailed);
}
defineExpose({ open })
</script>

<template>
  <a-drawer :maskClosable="false" :closable="false" destroyOnClose v-model:open="show" class="custom-class"
    root-class-name="root-class-name" :title="title" placement="right" @after-open-change="afterOpenChange">
    <a-form ref="formRef" :disabled="isDetail" :model="formData" layout="vertical" autocomplete="off" @finish="onFinish"
      @finishFailed="onFinishFailed">
      <a-form-item label="用户名称" name="name" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.name" />
      </a-form-item>
      <a-form-item label="用户角色" name="roles" :rules="[{ required: true, message: '请选择' }]">
        <ASelect v-model:value="formData.roles" :options="roleOpt" mode="multiple" allowClear />
      </a-form-item>
      <a-form-item label="用户邮箱" name="email" :rules="emailRule">
        <a-input v-model:value="formData.email" />
      </a-form-item>
      <a-form-item label="用户电话" name="phone" :rules="phoneRule">
        <a-input v-model:value="formData.phone" />
      </a-form-item>
      <a-form-item label="登录帐号" name="userName" :rules="[{ required: true, message: '请输入' }]">
        <a-input v-model:value="formData.userName" />
      </a-form-item>
      <a-form-item label="所属部门" name="departments">
        <a-cascader v-model:value="formData.departments" :options="depTreeOpt" allowClear expand-trigger="hover"
          :fieldNames="{ children: 'children', label: 'name', value: 'id' }" multiple :showSearch="true" change-on-select
          :show-checked-strategy="Cascader.SHOW_CHILD" />
      </a-form-item>
    </a-form>
    <template #footer>
      <template v-if="!isDetail">
        <div style="display: flex;gap: 5px">
          <a-button type="primary" html-type="submit" @click="submit" :loading="submitLoading">提交</a-button>
          <a-button type="primary" ghost @click="show = false">取消</a-button>
        </div>
      </template>
      <template v-else>
        <a-button type="primary" @click="close">关闭</a-button>
      </template>
    </template>
  </a-drawer>
</template>